<?php
namespace plugins\address\model;

use think\Model;

/**
 * 地址模型
 */
class AddressModel extends Model
{
    /**
     * 获取地址
     */
    public function getAddress()
    {
        $address = getModuleConfig('address', 'config', 'area.json');
        $address = json_decode($address, true);
        //设置缓存存活时间
        if (empty($address['area']) || $address['expiry_time'] < time()) {
            $this->updateConfig();
        }
        return $address['area'];
    }
    /**
     * 更新缓存
     */
    protected function updateConfig()
    {
        $da   = $this->getSubord();
        $data = [];
        foreach ($da as $key => $value) {
            $da1                 = [];
            $data[$key]['label'] = $value['cri_name'];
            $data[$key]['value'] = $value['cri_code'];
            $da1                 = $this->getSubord($value['cri_code']);
            if (!empty($da1)) {
                foreach ($da1 as $key1 => $value1) {
                    $da2                                    = [];
                    $data[$key]['children'][$key1]['label'] = $value1['cri_name'];
                    $data[$key]['children'][$key1]['value'] = $value1['cri_code'];
                    $da2                                    = $this->getSubord($value1['cri_code']);
                    if (!empty($da2)) {
                        foreach ($da2 as $key2 => $value2) {
                            $data[$key]['children'][$key1]['children'][$key2]['label'] = $value2['cri_name'];
                            $data[$key]['children'][$key1]['children'][$key2]['value'] = $value2['cri_code'];
                        }
                    }
                }
            }
        }
        $config = [
            'area'        => $data,
            'expiry_time' => time() + (86400 * 30), //设置失效时间为一个月
        ];
        saveModuleConfigData('address', 'config', 'area.json', $config);
        $this->success("更新缓存成功");
    }
    /**
     * 根据地区代码获取下级地区代码
     * @param    [str]   cri_code   [地区代码]    (可选)
     * @return   [arr]              [下级地区信息]
     */
    public function getSubord($cri_code = '000000')
    {
        $where = ['cri_superior_code' => $cri_code, 'status' => 1];
        $da    = $this->order('cri_sort', 'asc')->where($where)->select()->toArray();
        if (empty($da)) {
            return false;
        }
        $data = [];
        foreach ($da as $key => $value) {
            $data[$key]['cri_code'] = $value['cri_code'];
            $data[$key]['cri_name'] = $value['cri_name'];
            $data[$key]['cri_sort'] = $value['cri_sort'];
        }
        return $data;
    }
    /**
     * 输入地区编号  返回所有上级地区信息
     */
    public function findSuperior($cri_code = null, $i = 0, $return = [])
    {
        $da = $this->where('cri_code', (integer) $cri_code)->find();
        if (empty($da)) {
            return [];
        }
        $data       = $this->where('cri_code', (integer) $da['cri_superior_code'])->find();
        $i          = $i + 1;
        $return[$i] = $data;
        if (!empty((integer) $data['cri_superior_code'])) {
            $return = $this->findSuperior($da['cri_superior_code'], $i, $return);
        } else {
            return $return;
        }
        $return[0] = $da;
        return $return;
    }


    protected $update_level = 4; //更新五级地区

    /**
    1.缓存
    2.队列 ×
    3.分批次调用接口
    4.
     */

    /**
     * 更新数据
     */
    public function updateAddress($page = 1)
    {
        $path = "/areaName"; //areaName    areaDetail
        $querys = "level=1&page=" . $page; //areaName=%E4%B8%8A%E6%B5%B7%E5%B8%82&level=1&page=1    parentId=110000000000
        $param = $path . "?" . $querys;
        $data = $this->apiRequest($param);
        if ($data['ret_code'] == -1) {
            return zy_sys_echo(false, '查询数据失败', null, -1);
        }
        $allPage = $data['allPage']; //总页数
        if ($page <= $allPage) {
            foreach ($data['data'] as $key => $value) {
                $this->cityBelow( $value ); //处理市
                dump($value);
                exit;
            }
            if ($page < $allPage) {
                $this->updateAddress( $data['page'] + 1 );
            }
        }
        // //根据省查询下级数据
        exit;
    }

//     array(17) {
//   ["provinceId"] => string(12) "650000000000"
//   ["simpleName"] => string(6) "新疆"
//   ["lon"] => string(9) "43.793026"
//   ["cityId"] => string(0) ""
//   ["areaCode"] => string(0) ""
//   ["remark"] => string(0) ""
//   ["prePinYin"] => string(1) "X"
//   ["id"] => string(12) "650000000000"
//   ["pinYin"] => string(29) "xin jiang wei wu er zi zhi qu"
//   ["parentId"] => string(0) ""
//   ["level"] => int(1)
//   ["areaName"] => string(24) "新疆维吾尔自治区"
//   ["simplePy"] => string(2) "XJ"
//   ["zipCode"] => string(0) ""
//   ["countyId"] => string(0) ""
//   ["lat"] => string(9) "87.627704"
//   ["wholeName"] => string(31) "中国,新疆维吾尔自治区"
// }

    /**
     * 处理市
     */
    public function cityBelow($province = [])
    {
        //根据上级查询下级地区
        $path = "/areaDetail"; //areaName    areaDetail
        $querys = "parentId=".$province['id']; //areaName=%E4%B8%8A%E6%B5%B7%E5%B8%82&level=1&page=1    parentId=110000000000
        $param = $path . "?" . $querys;
        $data = $this->apiRequest($param);
        if ($data['ret_code'] == -1) {
            return zy_sys_echo(false, '查询数据失败', null, -1);
        }

        foreach ($data['data'] as $key => $value) {
            //层级限制
            if ($value['level'] < $this->update_level) {
                $this->countyBelow($value); //如果下级查询，则
                dump($value);
                exit;
            }
            
            $id = substr($value['id'], 0, 6);
            $parentId = substr($value['parentId'], 0, 6); //上级id
            $address  = db('address')->where('cri_code', $id)->find();

            $da = [
                'cri_code' => $id,
                'cri_name' => $value['areaName'],
                'cri_short_name' => $value['simpleName'],
                'cri_superior_code' => ($value['level'] == 1) ? '000000' : $parentId,
                'cri_lng' => $value['lon'],
                'cri_lat' => $value['lat'],
                'cri_sort' => '',
                // 'cri_gmt_create' => time(),
                'cri_gmt_modified' => date('Y-m-d H:i:s', time()),
                'cri_memo' => '',
                'cri_data_state' => 0,
                'cri_tenant_code' => '00000000',
                'cri_level' => $value['level'],
                'status' => 1,
            ];

            if (empty($address)) {
                $da['cri_gmt_create'] = date('Y-m-d H:i:s', time());
                db('address')->insert($da);
            } else {
                //修改地址
                db('address')->where(['cri_code' => $id])->update($da);
            }
        }

        $f_id = substr($province['id'], 0, 6);
        $f_parentId = substr($province['parentId'], 0, 6); //上级id
        //修改省级
        $pda = [
            'cri_code' => $f_id,
            'cri_name' => $province['areaName'],
            'cri_short_name' => $province['simpleName'],
            'cri_superior_code' => ($province['level'] == 1) ? '000000' : $f_parentId,
            'cri_lng' => $province['lon'],
            'cri_lat' => $province['lat'],
            'cri_sort' => '',
            // 'cri_gmt_create' => time(),
            'cri_gmt_modified' => date('Y-m-d H:i:s', time()),
            'cri_memo' => '',
            'cri_data_state' => 0,
            'cri_tenant_code' => '00000000',
            'cri_level' => $province['level'],
            'status' => 1,
        ];

        $prov = $this->where('cri_code', $f_id)->find();
        if (empty($prov)) {
            $pda['cri_gmt_create'] = date('Y-m-d H:i:s', time());
            db('address')->insert($pda);
        } else {
            db('address')->where(['cri_code' => $f_id])->update($pda);
        }
    }

    /**
     * 处理县
     */
    public function countyBelow($province = [])
    {
        

        //根据上级查询下级地区
        $path = "/areaDetail"; //areaName    areaDetail
        $querys = "parentId=".$province['id']; //areaName=%E4%B8%8A%E6%B5%B7%E5%B8%82&level=1&page=1    parentId=110000000000
        $param = $path . "?" . $querys;
        $data = $this->apiRequest($param);
        if ($data['ret_code'] == -1) {
            return zy_sys_echo(false, '查询数据失败', null, -1);
        }

        $f_id = substr($province['id'], 0, 6);
        $f_parentId = substr($province['parentId'], 0, 6); //上级id
        //修改省级
        $pda = [
            'cri_code' => $f_id,
            'cri_name' => $province['areaName'],
            'cri_short_name' => $province['simpleName'],
            'cri_superior_code' => ($province['level'] == 1) ? '000000' : $f_parentId,
            'cri_lng' => $province['lon'],
            'cri_lat' => $province['lat'],
            'cri_sort' => '',
            // 'cri_gmt_create' => time(),
            'cri_gmt_modified' => date('Y-m-d H:i:s', time()),
            'cri_memo' => '',
            'cri_data_state' => 0,
            'cri_tenant_code' => '00000000',
            'cri_level' => $province['level'],
            'status' => 1,
        ];
        // dump($province['level']);
        $prov = db('address')->where('cri_code', $f_id)->find();
        if (empty($prov)) {
            $pda['cri_gmt_create'] = date('Y-m-d H:i:s', time());
            db('address')->insert($pda);
            // $this->insert($pda);
        } else {
            db('address')->where(['cri_code' => $f_id])->update($pda);
        }

        foreach ($data['data'] as $key => $value) {

            dump($value);

            $id = substr($value['id'], 0, 6);
            dump($id);
            $parentId = substr($value['parentId'], 0, 6); //上级id

            $address  = db('address')->where('cri_code', $id)->find();
            // dump($address);
            $da = [
                'cri_code' => $id,
                'cri_name' => $value['areaName'],
                'cri_short_name' => $value['simpleName'],
                'cri_superior_code' => ($value['level'] == 1) ? '000000' : $parentId,
                'cri_lng' => $value['lon'],
                'cri_lat' => $value['lat'],
                'cri_sort' => '',
                // 'cri_gmt_create' => time(),
                'cri_gmt_modified' => date('Y-m-d H:i:s', time()),
                'cri_memo' => '',
                'cri_data_state' => 0,
                'cri_tenant_code' => '00000000',
                'cri_level' => $value['level'],
                'status' => 1,
            ];


            if (empty($address)) {

                // dump('添加'. $value['level']);
                $da['cri_gmt_create'] = date('Y-m-d H:i:s', time());
                db('address')->insert($da);
                // $this->insert($da);
            } else {

                // dump('修改'.json_encode($address, JSON_UNESCAPED_UNICODE).'--'. $value['level']);
                //修改地址
                db('address')->where(['cri_code' => $id])->update($da);
            }

            //层级限制
            if ($value['level'] < $this->update_level) {



                $this->countyBelow($value); //如果下级查询，则
            }

        }
        
    }




    /**
     * 接口请求
     */
    protected function apiRequest($param, $method = "GET")
    {
        $host = "https://ali-city.showapi.com";

        $url = $host . $param;

        $appcode = "aaae209d00534572a09764bb81f1e8c9"; 
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $data = curl_exec($curl);
        $data = json_decode($data, true);
        return $data['showapi_res_body'];
    }



}
